﻿using Finance.Web.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Finance.Web.Controllers
{
    public class DepositController : Controller
    {
         [Authorize]
        public ActionResult Index()
        {
            return PartialView();
        }

         [Authorize]
        public ActionResult Create()
        {
            return PartialView();
        }

         [Authorize]
        public ActionResult Query(string name, int offset, int count)
        {
            using (FinanceContext context = new FinanceContext())
            {
                IEnumerable<Deposit> models = context.Deposites.OrderBy(i => i.Name);
                if (name != null && name != string.Empty)
                    models = models.Where(i => i.Name.IndexOf(name, StringComparison.InvariantCultureIgnoreCase) != -1);

                models = models.Skip(offset).Take(count);

                return Json(models.Select(m => new DepositViewModel(m)).ToList());
            }
        }


         [Authorize]
        public ActionResult Save(Deposit model)
        {
            if (ModelState.IsValid)
            {
                using (FinanceContext context = new FinanceContext())
                {
                    if (model.Code != 0)
                    {
                        var exist = context.Deposites.FirstOrDefault(i => i.Code == model.Code);
                        if (exist == null)
                            return HttpNotFound();
                        else
                        {
                            exist.Name = model.Name;
                            exist.Info = model.Info;
                            exist.BankCode = model.BankCode;
                            exist.Capitalization = model.Capitalization;
                            exist.PaymentFrequesny = model.PaymentFrequesny;
                            exist.Percent = model.Percent;
                            exist.PeriodPayment = model.PeriodPayment;
                            exist.PercentAmountDepend = model.PercentAmountDepend;

                            List<PercentAmountDepend> newval = new List<PercentAmountDepend>();
                            for (int i = 0; i < exist.PercentAmountDepends.Count; i++)
                            {
                                var modelValue = model.PercentAmountDepends.FirstOrDefault(j => j.Code == exist.PercentAmountDepends.ElementAt(i).Code);
                                if (modelValue == null)
                                {
                                    context.PercentAmountDepends.Remove(exist.PercentAmountDepends.ElementAt(i));
                                    i--;
                                }
                                else
                                {
                                    var existValue = exist.PercentAmountDepends.ElementAt(i);
                                    existValue.MinAmount = modelValue.MinAmount;
                                    existValue.MaxAmount = modelValue.MaxAmount;
                                    existValue.Percent = modelValue.Percent;
                                    newval.Add(existValue);
                                }
                            }

                            exist.PercentAmountDepends = newval;
                            foreach (var item in model.PercentAmountDepends.Where(i => i.Code == 0))
                                exist.PercentAmountDepends.Add(item);

                            exist.HasPenalties = model.HasPenalties;

                            List<PercentPenalty> newvalpen = new List<PercentPenalty>();
                            for (int i = 0; i < exist.PercentPenalties.Count; i++)
                            {
                                var modelValue = model.PercentPenalties.FirstOrDefault(j => j.Code == exist.PercentPenalties.ElementAt(i).Code);
                                if (modelValue == null)
                                {
                                    context.PercentPenalties.Remove(exist.PercentPenalties.ElementAt(i));
                                    i--;
                                }
                                else
                                {
                                    var existValue = exist.PercentPenalties.ElementAt(i);
                                    existValue.From = modelValue.From;
                                    existValue.To = modelValue.To;
                                    existValue.Percent = modelValue.Percent;
                                    newvalpen.Add(existValue);
                                }
                            }

                            exist.PercentPenalties = newvalpen;
                            foreach (var item in model.PercentPenalties.Where(i => i.Code == 0))
                                exist.PercentPenalties.Add(item);

                            context.SaveChanges();
                            return new JsonResult();
                        }
                    }
                    else
                    {

                        var exist = context.Deposites.FirstOrDefault(i => i.Name == model.Name && i.BankCode == model.Bank.Code);
                        if (exist != null)
                            ModelState.AddModelError("Name", "Уже существует такой депозит");
                        else
                        {
                            model.Bank = context.Banks.FirstOrDefault(b => b.Code == model.Bank.Code);
                            context.Deposites.Add(model);
                            context.SaveChanges();
                            return new JsonResult();
                        }
                    }
                }
            }
            return Finance.Web.Utils.AngularFormErrors(this);
        }

         [Authorize]
        public ActionResult Get(int code)
        {
            using (FinanceContext context = new FinanceContext())
            {
                var model = context.Deposites.FirstOrDefault(i => i.Code == code);
                if (model != null)
                    return Json(new DepositViewModel(model));
                else
                    return HttpNotFound();
            }
        }

         [Authorize]
        public ActionResult Remove(Deposit model)
        {
            using (FinanceContext context = new FinanceContext())
            {
                var exist = context.Deposites.FirstOrDefault(i => i.Code == model.Code);
                if (exist != null)
                {
                    context.UserDeposites.RemoveRange(exist.UserDeposit);
                    context.PercentAmountDepends.RemoveRange(exist.PercentAmountDepends);
                    context.PercentPenalties.RemoveRange(exist.PercentPenalties);

                    exist.UserDeposit.Clear();
                    exist.PercentAmountDepends.Clear();
                    exist.PercentPenalties.Clear();

                    context.Deposites.Remove(exist);

                    context.SaveChanges();
                    return new JsonResult();
                }
                else
                    return HttpNotFound();
            }
        }
    }
}
